<?php

namespace backend\models\form;

use backend\models\AdminUser;
use Yii;
use yii\base\Model;
use common\service\BaseToolService ;

/**
 * Description of RetPasswordForm
 *
 * @author Administrator
 */
class ResetPasswordForm extends Model {

    public $old_password;
    public $new_password;
    public $confirm_password;

    private $_user = false;

    /**
     * 验证输入框的信息
     * @return type
     */
    public function rules() {
        return [
            [['new_password','old_password','confirm_password'],'required'] ,
            [['new_password','old_password','confirm_password'],'string'],
            [['new_password'], 'match','pattern' => '/^[a-zA-Z0-9\_\~\!\@\#\$\%\^\&\*\(\)\+\,\.\?]{6,20}$/','message' => '请输入6-20位字符.英文,数字,"~!@#$%^&*()_+,.?"的组合'],
            ['confirm_password', 'compare', 'compareAttribute'=>'new_password', 'message'=>'两次密码不一致'],
        ];
    }

    public function attributeLabels() {
        return [
            'new_password'=>'新密码',
            'old_password' => '旧密码' ,
            'confirm_password' => '确认密码' ,
        ];
    }

    /**
     * 修改密码
     * @param $user_id
     * @return array
     */
    public function retPassword($user_id)
    {
        $user = AdminUser::findOne(["user_id" => $user_id]);
        if (empty($user)) {
            return ["status" => false, "msg" => "无此用户"];
        }

        $en_old_password = BaseToolService::encodePassword($user->password_order, $this->old_password);

        if($en_old_password!==$user->password){
            return ["status"=>false,"msg"=>"原密码不正确"] ;
        }

        $en_password = BaseToolService::encodePassword($user->password_order, $this->new_password);
        $user->password = $en_password;
        $user->uptime = time() ;
        $add_rs = $user->save() ;

        if($add_rs==true){
            return ["status"=>true,"msg"=>"修改密码成功"] ;
        }else{
            return ["status"=>false,"msg"=>"修改密码失败"] ;
        }


    }

    private function getUser(){
        if ($this->_user === false) {
            $this->_user = User::findOne(["phone"=>$this->phone,"phone_status"=>1]) ;
        }
        return $this->_user;
    }

}
